package org.nudt.system.service

import cn.dev33.satoken.exception.SaTokenException
import cn.dev33.satoken.secure.SaSecureUtil
import org.nudt.common.exception.BadRequestException
import org.nudt.common.model.Admin
import org.nudt.common.model.dto.AdminDto
import org.nudt.system.repository.AdminRepository
import org.springframework.stereotype.Service

@Service
class SysAdminService(private val repository: AdminRepository) {
    
    fun getAdminById(id: Int): Admin? {
        val admin = repository.getAdminById(id)
        if (admin.isEmpty) {
            throw SaTokenException("管理员账户不存在")
        } else {
            return admin.get().copy(password = "")
        }
    }
    
    fun login(adminToLogin: AdminDto): Admin {
        val admin = repository.findByUsername(adminToLogin.username)
        if (admin.isEmpty) {
            throw SaTokenException("管理员账户不存在")
        } else {
            if (SaSecureUtil.sha256(adminToLogin.password) == admin.get().password) {
                return admin.get().copy(password = "")
            } else {
                throw SaTokenException("密码错误")
            }
        }
    }
    
    fun register(username: String, password: String): Admin {
        val admin = repository.findByUsername(username)
        if (admin.isPresent) {
            throw BadRequestException("username repeat")
        } else {
            val encryptedPassword = SaSecureUtil.sha256(password)
            val newAdmin = Admin(username = username, password = encryptedPassword)
            return repository.save(newAdmin)
        }
    }
}